package com.css.devops.service.jenkins;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.css.devops.component.JenkinsBasicComponent;
import com.css.devops.constants.DevopsConstants;
import com.css.devops.service.DevopsViewManager;
import com.google.common.collect.Maps;

import cn.hutool.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("jenkinsViewManagerService")
public class JenkinsViewManagerService implements DevopsViewManager {

    @Autowired
    private JenkinsBasicComponent jenkinsBasicComponent;
    
    /**
     * 使用 HTTP 请求将 Job 添加到 View 中
     * @param viewName
     * @param jobName
     */
    @Override
	public int addJobToView(String viewName, String jobName) {
    	int responseCode = HttpStatus.OK.value();
        try {
        	String endPoint = String.format(DevopsConstants.JENKINS_ADD_JOB_2_VIEW, viewName);
            Map<String,String> forms = Maps.newConcurrentMap();
            forms.put("name", jobName);
            HttpResponse response = jenkinsBasicComponent.postRequest(endPoint, forms);
            // 检查响应码
            responseCode = response.getStatus();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return responseCode;
    }
    
    /**
     * 使用 HTTP 请求将 Job 从 View 中移除
     */
    @Override
	public int removeJobFromView(String viewName, String jobName) {
    	int responseCode = HttpStatus.OK.value();
        try {
            String endPoint = String.format(DevopsConstants.JENKINS_REMOVE_JOB_2_VIEW, viewName);
            Map<String,String> forms = Maps.newConcurrentMap();
            forms.put("name", jobName);
            HttpResponse response = jenkinsBasicComponent.postRequest(endPoint, forms);

            // 检查响应码
            responseCode = response.getStatus();
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
        }
        return responseCode;
    }
}



